import React, { useState, useEffect } from 'react'
import style from './Index.module.less'
import { Row, Col, Form, message, AutoComplete, InputNumber, Input, DatePicker, Button, Space } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import Text from '@components/Text'
import { awaitWrap, confirmAction, strToNum } from '@src/assets/js/tool'
import { addRequest, updateRequest, getRequest, getCauseRequest } from './ajax'
import MoneyInput from '@components/MoneyInput/Index'
import PartyList from './components/PartyList/Index'
import { useDispatch } from 'react-redux'
import moment from 'moment'
import { delWindow, refreshWindow, setActiveWindowId } from '@src/redux/actions'
import lodash from 'loadsh'

const { TextArea } = Input

async function initData (id, formRef) {
  const h = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getRequest(id))
  h()
  if (e === null && d !== null) {
    d.closure_datetime = strToNum(d.closure_datetime)
    if (d.closure_datetime) {
      d.closure_datetime = moment(d.closure_datetime * 1000)
    }
    formRef.setFieldsValue(d)
  }
}

async function initCauseHandle (search, setData, setLoading) {
  setLoading(true)
  setData([])
  const [e, d] = await awaitWrap(getCauseRequest(search))
  setLoading(false)
  if (e) {
    return message.warning(e.message)
  }
  setData(d)
}

const initCauseHandle_ = lodash.debounce(initCauseHandle, 600)

async function submitHandle (d, id, dispatch) {
  let url = addRequest
  if (d.id) {
    url = updateRequest
  }
  formatSubmitData(d)
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(url(d))
  h()
  if (e === null) {
    message.success(d.id ? '更新成功' : '新建成功')
    dispatch(delWindow(id))
    dispatch(refreshWindow('AllTJCaseManage'))
    dispatch(setActiveWindowId('AllTJCaseManage'))
  }
}

function formatSubmitData (d) {
  delete d.caseno_desc
  if (d.closure_datetime instanceof moment) {
    d.closure_datetime = Math.floor(d.closure_datetime.valueOf() / 1000)
  }
  if (!d.claim) {
    d.claim = null
  }
}

const { Item } = Form

function Main ({ title, meta, id }) {
  const dispatch = useDispatch()
  const [formRef] = Form.useForm()
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(false)
  const [options, setOptions] = useState([])
  const [caseid, setCaseid] = useState('')
  useEffect(() => {
    initCauseHandle_(search, setOptions, setLoading)
  }, [search])
  useEffect(() => {
    if (meta.id) {
      setCaseid(meta.id)
      initData(meta.id, formRef)
    }
  }, [meta, formRef])
  const notFound = (
    loading ? (
      <div className={style.loading}><LoadingOutlined className={style['loading-ico']} /><span>加载中</span></div>
    ) : (
      <div className={style['no-found']}>暂无数据</div>
    )
  )
  return (
    <div className={style.container}>
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <div className={style.body}>
        <Form form={formRef} labelCol={{ flex: '120px' }} onFinish={d => submitHandle(d, id, dispatch)}>
          <Item noStyle name='id'><span /></Item>
          {
            caseid && (
              <Row gutter={24}>
                <Col span={6} />
                <Col span={10}>
                  <Item label='案号' name='caseno_desc'>
                    <Text format={v => v || '无'} />
                  </Item>
                </Col>
              </Row>
            )
          }
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='cause_action' label='案由' rules={[{ required: true, message: '案由不能为空' }]}>
                <AutoComplete options={options} className={style.full} onSearch={e => setSearch(e)} placeholder='请输入' notFoundContent={notFound} />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='applicant' label='申请人' rules={[{ required: true, message: '申请人不能为空' }]}>
                <PartyList type='申请人' />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='respondent' label='被申请人' rules={[{ required: true, message: '被申请人不能为空' }]}>
                <PartyList type='被申请人' />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='dispute_amount' label='和解金额' rules={[{ required: true, message: '和解金额不能为空' }]}>
                <MoneyInput placeholder='请输入' config={{}} />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='claim_items' label='和解事项'>
                <InputNumber placeholder='请输入' max={1000} min={0} addonAfter='项' className={style.full} />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='claim' label='和解内容'>
                <TextArea placeholder='请输入' autoSize={{ minRows: 3 }} allowClear />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='arbitrator' label='仲裁调解员'>
                <Input placeholder='请输入' allowClear />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='closure_datetime' label='和解时间' rules={[{ required: true, message: '和解时间不能为空' }]}>
                <DatePicker placeholder='请选择' allowClear className={style.full} />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='docket_remark' label='立案部意见' rules={[{ required: true, message: '立案部意见不能为空' }]}>
                <TextArea placeholder='请输入' autoSize={{ minRows: 3 }} allowClear />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item name='audit_remark' label='秘书长意见' rules={[{ required: true, message: '秘书长意见不能为空' }]}>
                <TextArea placeholder='请输入' autoSize={{ minRows: 3 }} allowClear />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col span={6} />
            <Col span={10}>
              <Item label=' ' colon={false}>
                <Space>
                  <Button
                    htmlType='button'
                    type='primary' onClick={() => {
                      confirmAction('您确定要提交吗？', () => formRef.submit())
                    }}
                  >提交
                  </Button>
                  <Button
                    htmlType='button' onClick={() => {
                      dispatch(delWindow(id))
                      dispatch(setActiveWindowId('AllTJCaseManage'))
                    }}
                  >取消
                  </Button>
                </Space>
              </Item>
            </Col>
          </Row>
        </Form>
      </div>
    </div>
  )
}

export default Main
